<template>
    <div class="pop-good-filling">
        <div class="context-box comm-list">
            <div class="good-info">
                <div class="img-box">
                    <img :src="info_data.imgs ? info_data.imgs[0] : img_buf" />
                </div>
                <div class="info-box">
                    <div class="title bold">{{ info_data.title || '--' }}</div>
                    <div class="">{{ info_data.gd_brand || '--' }}</div>
                    <div class="mt5">
                        <span class="">价格：<span class="bold font_red">￥{{ info_data.price || '--' }}</span></span>
                        <span class="qty ml20">库存：{{ info_data.qty || '--' }}</span>
                    </div>
                    <div class="">单位：{{ info_data.unit || '--' }}</div>
                </div>
            </div>
            <div class="store-box mt10" v-if="storeList && storeList.length > 0">
                <el-collapse accordion>
                    <el-collapse-item>
                        <template slot="title">
                            <span class="mr5">仓库库存</span>
                            <i class="header-icon el-icon-info"></i>
                        </template>
                        <div class="store-item flex_between" v-for="(store, s_index) in storeList" :key="s_index"
                            :class="s_index % 2 === 0 ? 'even-item' : 'odd-item'">
                            <div class="store-cell">名称：{{ store.store_name }}</div>
                            <div class="store-cell ml30">库存：{{ store.qty_min }}</div>
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </div>
            <div class="spec-pic-box" v-if="spec_data1.length > 0">
                <div class="spec-box-1">
                    <div class="spec-row" v-for="(item, index) in spec_data1" :key="index"
                        :class="item.is_acitve ? 'acitve' : ''" @click="switchSkuFun1(item)">
                        <span>{{ item.title }}</span>
                        <span>{{ item.all_num > 0 ? `(${item.all_num})` : "" }}</span>
                    </div>
                </div>
                <div class="spec-box-2" v-show="spec_data2.length > 0">
                    <div class="spec-row" v-for="(item, index) in spec_data2" :key="index"
                        :class="item.is_acitve ? 'acitve' : ''" @click="switchSkuFun2(item)">
                        <span> {{ item.title }} </span>
                        <span> {{ item.all_num > 0 ? `(${item.all_num})` : "" }} </span>
                    </div>
                </div>
                <div class="spec-box-3">
                    <div class="spec-row" v-for="(item, index) in spec_data3" :key="index">
                        <div class="spec-title" v-if="item.title">{{ item.title }}</div>
                        <div class="unit-row" v-for="(item_unit, index_unit) in item.unit_ls" :key="index_unit">
                            <div class="flex_row">
                                <div class="input-box">
                                    <div class="input-pic">
                                        <span class="title-pic">{{titleTName}}价：</span>
                                        <el-input v-model="item_unit.price"
                                            @input="(value) => handlePriceInput(index, index_unit, value)" size="small"
                                            class="input-w" placeholder="请输入价" :disabled="!LIMIT_STOREKEEEPER_EDIT_PRICE"></el-input>
                                    </div>
                                    <div class="">
                                        <span class="title-pic">数量：</span>
                                        <el-input-number v-model="item_unit.number" size="small" :min="0"
                                            @change="changeQuantity(item_unit)"></el-input-number>
                                    </div>
                                </div>
                                <div class="unit-title">（{{ item_unit.title || '--' }}）</div>
                            </div>
                            <div class="txt-box">
                                <div class="title-txt">备注：</div>
                                <el-input v-model="item_unit.txt" size="small" class="input-w"
                                    placeholder="请输入备注信息（200字内）" maxlength="200" show-word-limit></el-input>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <div class="summary-info">
                <div class="summary-item">
                    <span class="summary-label">数量</span>
                    <span class="summary-value quantity">{{ isNaN(totalNum) ? 0 : totalNum }}</span>
                </div>
                <div class="summary-divider"></div>
                <div class="summary-item">
                    <span class="summary-label">总额</span>
                    <span class="summary-value amount">￥{{ isNaN(totalpic) ? '0.00' : parseFloat(totalpic).toFixed(2)
                    }}</span>
                </div>
            </div>
            <div class="action-buttons">
                <el-button @click="cancelFun" size="small" class="btn-cancel">取 消</el-button>
                <el-button type="danger" @click="emptyFilling" size="small" class="btn-clear">清 空</el-button>
                <el-button type="primary" @click="submitHandle" size="small" class="btn-confirm">确 定</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, computed, defineProps } from '@vue/composition-api'
import config from "@/js/conf/Config.js";
import staticConst from "@/js/const/StaticConst.js";
import { generateRandom4Digits, priceInput } from '@/utils/common.js'
const { proxy } = getCurrentInstance()
import accessCtrl from "@/js/limit/AccessCtrl.js"; // 检测权限

const props = defineProps({
    tabType: {
        type: String,
        default: '',
    },
})

const titleTName = computed(() => {
    return props?.tabType == 'into_warehouse' ? '入库' :
        props?.tabType == 'transfer_warehouse' ? '调拨' :
            props?.tabType == 'out_warehouse' ? '出库' : ''
})

// 响应式数据
const img_buf = ref(staticConst.GOOD_IMG)
const info_data = ref({})
const sku_list_data = ref([])
const gd_data = ref({})
const spec_data1 = ref([]) //sku总数据(一级)
const spec_data2 = ref([]) //(二级)
const spec_data3 = ref([]) //(三级)
const storeList = ref([])

// 计算属性
const totalNum = computed(() => {
    let num = 0;
    if (!spec_data1.value || !Array.isArray(spec_data1.value)) {
        return 0;
    }
    spec_data1.value.forEach((v) => {
        if (v && v.list) {
            v.list.forEach((vs) => {
                if (vs && vs.list) {
                    vs.list.forEach((vw) => {
                        if (vw && vw.unit_ls && Array.isArray(vw.unit_ls)) {
                            vw.unit_ls.forEach((vk) => {
                                if (vk && vk.number !== undefined && vk.number !== null) {
                                    num += Number(vk.number) || 0;
                                }
                            });
                        }
                    });
                } else if (vs && vs.unit_ls && Array.isArray(vs.unit_ls)) {
                    vs.unit_ls.forEach((vw) => {
                        if (vw && vw.number !== undefined && vw.number !== null) {
                            num += Number(vw.number) || 0;
                        }
                    });
                }
            });
        } else if (v && v.unit_ls && Array.isArray(v.unit_ls)) {
            v.unit_ls.forEach((vs) => {
                if (vs && vs.number !== undefined && vs.number !== null) {
                    num += Number(vs.number) || 0;
                }
            });
        }
    });
    return num;
})

const totalpic = computed(() => {
    let num = 0;
    if (!spec_data1.value || !Array.isArray(spec_data1.value)) {
        return 0;
    }
    spec_data1.value.forEach((v) => {
        if (v && v.list) {
            v.list.forEach((vs) => {
                if (vs && vs.list) {
                    vs.list.forEach((vw) => {
                        if (vw && vw.unit_ls && Array.isArray(vw.unit_ls)) {
                            vw.unit_ls.forEach((vk) => {
                                if (vk && vk.price !== undefined && vk.price !== null && vk.number !== undefined && vk.number !== null) {
                                    num += (Number(vk.price) || 0) * (Number(vk.number) || 0);
                                }
                            });
                        }
                    });
                } else if (vs && vs.unit_ls && Array.isArray(vs.unit_ls)) {
                    vs.unit_ls.forEach((vw) => {
                        if (vw && vw.price !== undefined && vw.price !== null && vw.number !== undefined && vw.number !== null) {
                            num += (Number(vw.price) || 0) * (Number(vw.number) || 0);
                        }
                    });
                }
            });
        } else if (v && v.unit_ls && Array.isArray(v.unit_ls)) {
            v.unit_ls.forEach((vs) => {
                if (vs && vs.price !== undefined && vs.price !== null && vs.number !== undefined && vs.number !== null) {
                    num += (Number(vs.price) || 0) * (Number(vs.number) || 0);
                }
            });
        }
    });
    return num;
})

const handlePriceInput = (index, index_unit, value) => {
    // 使用 priceInput 函数处理输入值
    const processedValue = priceInput(value);
    if (spec_data3.value && spec_data3.value[index] && spec_data3.value[index].unit_ls) {
        const currentUnit = spec_data3.value[index].unit_ls[index_unit];
        if (currentUnit) {
            currentUnit.price = processedValue;
        }
    }
    recalculateAllNums();
}

// 事件定义
const emit = defineEmits(['cancelFun', 'determineFilling'])

// 方法
const initData = async (data) => {
    emptyData();
    gd_data.value = data;
    await getGoodInfo();
    await getGoodspecInfo();
}

const editSkuinfo = async (data) => {
    emptyData();
    spec_data1.value = data.spec_data;
    switchSkuFun1(data.spec_data[0]);
    gd_data.value = data;
    await getGoodInfo();
    // 重新计算总数
    recalculateAllNums();
}

// 改变数量
let quantityChangeTimer = null
const changeQuantity = (item) => {
    // 清除之前的定时器
    if (quantityChangeTimer) {
        clearTimeout(quantityChangeTimer)
    }
    // 设置新的定时器，300ms 后执行
    quantityChangeTimer = setTimeout(() => {
        // 重新计算所有规格的总数
        recalculateAllNums()
    }, 300)
}

// 重新计算所有规格的总数量
const recalculateAllNums = () => {
    spec_data1.value.forEach((spec1) => {
        let spec1Total = 0
        if (spec1.list) {
            // 有二级规格
            spec1.list.forEach((spec2) => {
                let spec2Total = 0
                if (spec2.list) {
                    // 有三级规格
                    spec2.list.forEach((spec3) => {
                        let spec3Total = 0
                        if (spec3.unit_ls) {
                            spec3Total = spec3.unit_ls.reduce((sum, unit) => sum + (Number(unit.number) || 0), 0)
                        }
                        spec3.all_num = spec3Total
                        spec2Total += spec3Total
                    })
                } else {
                    // 只有二级规格
                    if (spec2.unit_ls) {
                        spec2Total = spec2.unit_ls.reduce((sum, unit) => sum + (Number(unit.number) || 0), 0)
                    }
                }
                spec2.all_num = spec2Total
                spec1Total += spec2Total
            })
        } else {
            // 只有一级规格
            if (spec1.unit_ls) {
                spec1Total = spec1.unit_ls.reduce((sum, unit) => sum + (Number(unit.number) || 0), 0)
            }
        }
        spec1.all_num = spec1Total
    })
}

// 选择一级规格
const switchSkuFun1 = (item) => {
    spec_data1.value.map((v) => {
        if (v.id == item.id) {
            v.is_acitve = true;
        } else {
            v.is_acitve = false;
        }
    });
    if (item.list) {
        item.list.map((v, i) => {
            if (i == 0) {
                v.is_acitve = true;
            } else {
                v.is_acitve = false;
            }
        });
        spec_data2.value = item.list;
        if (item.list[0].list) {
            spec_data3.value = item.list[0].list;
        } else {
            spec_data3.value = [
                {
                    unit_ls: item.list[0].unit_ls,
                },
            ];
        }
    } else {
        spec_data2.value = [];
        spec_data3.value = [
            {
                unit_ls: item.unit_ls,
            },
        ];
    }
}

// 选择二级规格
const switchSkuFun2 = (item) => {
    spec_data2.value.map((v) => {
        if (v.id == item.id) {
            v.is_acitve = true;
        } else {
            v.is_acitve = false;
        }
    });
    if (item.list) {
        spec_data3.value = item.list;
    } else {
        spec_data3.value = [
            {
                unit_ls: item.unit_ls,
            },
        ];
    }
}

// 选择价格档
const commandFun = (item, val) => {
    item.price = val;
    item.pricec = val;
}

// 获取产品规格详情
const getGoodspecInfo = async () => {
    if (gd_data.value.spec_data) {
        spec_data1.value = gd_data.value.spec_data;
        switchSkuFun1(gd_data.value.spec_data[0]);
    } else {
        let url = config.GOODSINFO_GOODS_SPEC;
        let param = {
            goods_id: gd_data.value.id,
            ch: 4,
        };
        let res = await proxy.$api({ url: url, data: param });
        storeList.value = res.data?.store?.list;
        if (res.status == 1 && res.data) {
            // if (res.data.price_ls.price_ls && res.data.price_ls.gd_price) {
            //     res.data.price_ls.price_ls.map((v) => {
            //         if (v?.prices) {
            //             v.prices.map((vs) => {
            //                 res.data.price_ls.gd_price.map((vw) => {
            //                     if (vs.price_i == vw.psort) {
            //                         vs.title = vw.title;
            //                     }
            //                 });
            //             });
            //         }
            //     });
            // }
            if (res.data.unit_ls) {
                res.data.unit_ls.map((v, i) => {
                    if (res.data.price_ls.price_ls) {
                        res.data.price_ls.price_ls.map((vs) => {
                            if (v.unit_id == vs.unitid) {
                                v.prices = vs.prices;
                            }
                            // vs?.prices?.map((vw, vi) => {
                            //     if (i == vi) {
                            //         v.price = vw.price;
                            //         v.pricec = vw.price;
                            //         v.number = 0;
                            //     }
                            // });
                        });
                    }
                });
            }
            if (res.data.spec_ls) {
                res.data.spec_ls.map((v, i) => {
                    if (i == 0) {
                        v.is_acitve = true;
                    } else {
                        v.is_acitve = false;
                    }
                    v.all_num = 0;
                    if (v.list) {
                        v.list.map((vs, vi) => {
                            if (vi == 0) {
                                vs.is_acitve = true;
                            } else {
                                vs.is_acitve = false;
                            }
                            vs.all_num = 0;
                            if (vs.list) {
                                vs.list.map((vw) => {
                                    vw.unit_ls = [];
                                    res.data.unit_ls.map((vu) => {
                                        vw.unit_ls.push({
                                            md: "xs",
                                            img: gd_data.value.imgs,
                                            gd_title: gd_data.value.title,
                                            gdid: gd_data.value.id,
                                            price: vu?.prices,
                                            pricec: vu?.pricec,
                                            number: vu?.number,
                                            ismin: vu?.ismin,
                                            title: vu?.title,
                                            unit_id: vu?.unit_id,
                                            vch: vu?.vch,
                                            prices: vu?.prices,
                                            is_acitve: false,
                                            fid: vs?.id,
                                            did: vs?.fid,
                                            spec_dir: `${vs?.fid},${vs?.id}`,
                                            specid: vw?.id,
                                            doc: `${v?.title}|${vs?.title}|${vw?.title}`,
                                            txt: "",
                                        });
                                    });
                                });
                            } else {
                                vs.unit_ls = [];
                                res.data.unit_ls.map((vu) => {
                                    vs.unit_ls.push({
                                        md: "xs",
                                        img: gd_data.value.imgs,
                                        gd_title: gd_data.value.title,
                                        gdid: gd_data.value.id,
                                        price: vu?.prices,
                                        pricec: vu.pricec,
                                        number: vu.number,
                                        ismin: vu.ismin,
                                        title: vu.title,
                                        unit_id: vu.unit_id,
                                        vch: vu.vch,
                                        prices: vu.prices,
                                        is_acitve: false,
                                        fid: vs.id,
                                        did: vs.fid,
                                        spec_dir: vs.fid,
                                        specid: vs.id,
                                        doc: `${v.title}|${vs.title}`,
                                        txt: "",
                                    });
                                });
                            }
                        });
                    } else {
                        v.unit_ls = [];
                        res.data.unit_ls.map((vu) => {
                            v.unit_ls.push({
                                md: "xs",
                                img: gd_data.value.imgs,
                                gd_title: gd_data.value.title,
                                gdid: gd_data.value.id,
                                price: vu?.prices,
                                pricec: vu.pricec,
                                number: vu.number,
                                ismin: vu.ismin,
                                title: vu.title,
                                unit_id: vu.unit_id,
                                vch: vu.vch,
                                prices: vu.prices,
                                is_acitve: false,
                                fid: v.id,
                                spec_dir: "",
                                specid: v.id,
                                doc: v.title,
                                txt: "",
                            });
                        });
                    }
                });
                spec_data1.value = res.data.spec_ls;
                switchSkuFun1(res.data.spec_ls[0]);
                // 初始化后重新计算总数
                recalculateAllNums();
            }
        }
    }
}

// 获取产品详情
const getGoodInfo = async () => {
    let param = {
        goods_id: gd_data.value.id || gd_data.value.gdid,
    };
    let res = await proxy.$api({ url: config.GOODSINFO_GOODS_DETAIL, data: param });
    if (res.status == 1) {
        if (res.data.goodsInfo) {
            info_data.value = res.data.goodsInfo;
        }
    }
}

// 清空数据(初始化)
const emptyData = () => {
    info_data.value = {};
    sku_list_data.value = [];
    spec_data1.value = [];
    spec_data2.value = [];
    spec_data3.value = [];
    gd_data.value = {};
}

// 取消按钮
const cancelFun = () => {
    emit("cancelFun");
}

// 清空按钮
const emptyFilling = async () => {
    proxy.$confirm("确认清空当前填写的内容?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
    })
        .then(async () => {
            await getGoodInfo();
            await getGoodspecInfo();
        })
        .catch(() => { });
}

// 确定按钮
const submitHandle = () => {
    if (totalNum.value == 0) {
        proxy.$msg({ title: "请添加开单产品数量" });
        return;
    }
    const data = {
        spec_data: spec_data1.value,
        id: gd_data.value.id,
        total_num: parseInt(totalNum.value),
        total_pic: parseFloat(totalpic.value.toFixed(2)),
    };
    emit("determineFilling", data);
}

const LIMIT_STOREKEEEPER_EDIT_PRICE = ref(false); //单据经手人可改
const initPermission = async () => {
  LIMIT_STOREKEEEPER_EDIT_PRICE.value =  await accessCtrl.getStorekeeperEditPriceLimit(); //单据经手人可改
}
initPermission()

// 暴露给父组件的方法
defineExpose({
    initData,
    editSkuinfo
})
</script>

<style lang="scss" scoped>
.pop-good-filling {
    .context-box {
        height: 610px;
        overflow: auto;
        font-size: 14px;

        .good-info {
            padding: 10px;
            display: flex;
            border-radius: 5px;
            background: #f2f2f2;
            margin-bottom: 10px;

            .img-box {
                width: 100px;
                height: 100px;
                border-radius: 5px;
                overflow: hidden;
                margin-right: 10px;
                background: #eaeaea;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }

            .info-box {
                width: calc(100% - 110px);
            }
        }
    }

    .dialog-footer {
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 14px;
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

        .summary-info {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .summary-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .summary-label {
            font-size: 14px;
            color: #64748b;
            font-weight: 500;
        }

        .summary-value {
            font-size: 16px;
            font-weight: 600;
        }

        .summary-value.quantity {
            color: #0f172a;
        }

        .summary-value.amount {
            color: #e11d48;
            font-weight: 700;
            text-shadow: 0 1px 2px rgba(225, 29, 72, 0.1);
        }

        .summary-divider {
            width: 1px;
            height: 20px;
            background-color: #cbd5e1;
        }

        .action-buttons {
            display: flex;
            gap: 12px;
        }

        .btn-cancel {
            border-color: #cbd5e1;
            color: #64748b;
        }

        .btn-clear {
            background-color: #ef4444;
            border-color: #ef4444;
        }

        .btn-confirm {
            background-color: #3b82f6;
            border-color: #3b82f6;
        }
    }

    .spec-pic-box {
        margin-top: 5px;
        // background-color: rgba(222, 236, 255, 0.12);
        border-radius: 2px;
        border: 1px solid #cbd5e1;

        .spec-box-1 {
            display: flex;
            flex-wrap: wrap;
            padding: 10px;
            padding-bottom: 0;
            margin-bottom: 10px;
            // border-bottom: 1px solid #ede7e7;

            .spec-row {
                margin-bottom: 10px;
                cursor: pointer;
                margin-right: 20px;
                position: relative;

                &.acitve {
                    pointer-events: none;
                    color: #3388ff;

                    &::after {
                        content: " ";
                        position: absolute;
                        left: calc(50% - 3px);
                        bottom: -6px;
                        width: 6px;
                        height: 6px;
                        background: #3388ff;
                        border-radius: 50%;
                    }
                }
            }
        }

        .spec-box-2 {
            display: flex;
            flex-wrap: wrap;
            padding: 10px;
            padding-bottom: 0;
            margin-bottom: 10px;
            border-bottom: 1px solid #ede7e7;

            .spec-row {
                margin-bottom: 10px;
                cursor: pointer;
                margin-right: 20px;
                display: flex;
                justify-content: center;
                align-items: center;
                border-radius: 5px;
                padding: 0 10px;
                border: 1px solid #3388ff;
                color: #3388ff;

                &.acitve {
                    background: #3388ff;
                    color: #fff;
                    pointer-events: none;
                }
            }
        }

        .spec-box-3 {
            .spec-row {
                .spec-title {
                    background: #f2f2f2;
                    padding: 10px;
                    display: flex;
                    align-items: center;
                    margin-top: 20px;
                }

                .unit-row {
                    padding: 10px;
                    margin-bottom: 10px;
                    padding-bottom: 20px;
                    border-bottom: 1px solid #eaeaea;

                    .input-box {
                        display: flex;

                        .input-pic {
                            display: flex;
                            align-items: center;
                            margin-right: 20px;

                            .input-w {
                                width: 200px;
                            }

                            .ac-select {
                                cursor: pointer;

                                i {
                                    margin-left: 3px;
                                }
                            }

                            .price-files {
                                .price-files-row {
                                    margin-bottom: 10px;

                                    &:last-child {
                                        margin: 0;
                                    }
                                }
                            }
                        }
                    }

                    .txt-box {
                        margin-top: 10px;
                        display: flex;

                        .title-txt {
                            width: 56px;
                            text-align: justify;
                            text-align-last: justify;
                        }

                        .input-w {
                            width: calc(100% - 70px);
                        }
                    }
                }
            }
        }
    }
}

::v-deep .el-input-number {
    padding-left: 0 !important;
    padding-right: 0 !important;
    width: 200px !important;

    .el-input__inner {
        padding-left: 0 !important;
        padding-right: 0 !important;
    }
}

.store-item {
    padding: 0 10px;
    border-radius: 6px;
    transition: all 0.2s ease;
    align-items: center;

    .store-cell {
        flex: 0.5;
        text-align: left;
    }
}

::v-deep .el-collapse-item__content {
    padding-bottom: 10px !important;
}
</style>
